package openhaven.control;

import java.io.IOException;
import java.net.InetAddress;
import java.util.concurrent.BlockingQueue;

import openhaven.control.net.AuthClient;
import openhaven.control.net.Message;
import openhaven.control.net.Session;

import org.apache.log4j.Logger;

public class LoginTask implements Runnable
{
    private static final Logger LOG = Logger.getLogger(LoginTask.class);
    private final String host;
    private final String username;
    private final String password;
    private final BlockingQueue<Message> uiMessageQueue;

    public LoginTask(final String host, final String username, final String password, final BlockingQueue<Message> uiMessageQueue)
    {
        this.host = host;
        this.username = username;
        this.password = password;
        this.uiMessageQueue = uiMessageQueue;
    }

    @Override
    public void run()
    {
        LoginTask.LOG.debug("done login, " + username + ":" + password);
        try
        {
            final AuthClient authClient = new AuthClient(host, username);
            try
            {
                if (authClient.trypasswd(password))
                {
                    final byte[] cookie = authClient.cookie;
                    new Session(InetAddress.getByName(host), username, cookie, uiMessageQueue);
                }
            }
            finally
            {
                authClient.close();
            }
        }
        catch (final IOException e)
        {
            e.printStackTrace();
        }
    }

}
